package com.spzx.common.rabbit.config;

import ch.qos.logback.core.util.TimeUtil;
import com.spzx.common.rabbit.entity.GuiguCorrelationData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.sql.Time;
import java.util.concurrent.TimeUnit;

/**
 * 服务器启动时，执行rabbitTemplate初始化，设置确认函数和回退函数
 * ApplicationEvent      一些子事件的父类。
 * ApplicationReadyEvent 具体子事件。表示应用程序启动好，IOC容器初始化好，存在相关bean对象了。再进行相关的初始化。
 * 也可以使用相关的注解替代： @EventListener
 */
@Slf4j
@Component
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setUpInitRabbitTemplete();
    }


    private void setUpInitRabbitTemplete() {
        //确认回调函数
        rabbitTemplate.setConfirmCallback((correlationData, ack,cause)->{
            log.info("correlationData={}"+correlationData);
            if (ack){
                //为true表示交换机收到消息
                log.info("交换机收到消息了");
            }else{
                //交换机未收到消息
                log.info("交换机没有收到消息 cause:"+cause);

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //重发消息:交换机没收到
                retrySendMsg(correlationData);
            }
        });

        //回退回调函数
        //发送延迟消息,会导致回退回调函数被执行,会导致重试
        //问题解决:普通消息需要重试,延迟消息不再重试

        rabbitTemplate.setReturnsCallback((returnedMessage)->{

            log.info("returnedMessage:"+returnedMessage);//从响应消息对象头中获取关联数据的id值,头的名称:spring_returned_message_correlation

            //重发消息:队列没收到 利用缓存的关联的数据进行重发
            String uuid=returnedMessage.getMessage().getMessageProperties().getHeader("spring_returned_message_correlation");
            GuiguCorrelationData correlationData = (GuiguCorrelationData) redisTemplate.opsForValue().get(uuid);
            if (correlationData!=null && ! correlationData.isDelay()){
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                retrySendMsg(correlationData);
            }
        });

    }

    //重试方法
    private void retrySendMsg(CorrelationData correlationData) {
        GuiguCorrelationData guiguCorrelationData = (GuiguCorrelationData) correlationData;

        int retryCount = guiguCorrelationData.getRetryCount();
        if (retryCount>=3){
            log.info("达到消息最大重试次数");
            return;
        }
        retryCount ++;
        guiguCorrelationData.setRetryCount(retryCount);

        redisTemplate.opsForValue().set(guiguCorrelationData.getId(),guiguCorrelationData,10, TimeUnit.MINUTES);

        rabbitTemplate.convertAndSend(guiguCorrelationData.getExchange(),
                guiguCorrelationData.getRoutingKey(),
                guiguCorrelationData.getMessage(),
                guiguCorrelationData);

    }


}
